package org.iartisan.wechatsdk.miniprogram.res

import java.lang.reflect.Type

import com.google.gson.annotations.JsonAdapter
import com.google.gson.{JsonDeserializationContext, JsonDeserializer, JsonElement}
import org.iartisan.wechatsdk.common.res.WechatResError

import scala.beans.BeanProperty

/**
  * 小程序 code2Session 返回
  *
  * @author King  2019/6/17
  */
@JsonAdapter(classOf[Code2SessionAdapter])
class Code2SessionRes extends WechatResError {

  @BeanProperty
  var openid = ""

  @BeanProperty
  var sessionKey = ""

  @BeanProperty
  var unionid = ""

}

class Code2SessionAdapter extends JsonDeserializer[Code2SessionRes] {
  override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext) = {
    val res = new Code2SessionRes
    val jsonObj = json.getAsJsonObject
    val errcode = jsonObj.get("errcode")
    res.setErrcode(if (null == errcode) 0 else errcode.getAsInt)
    res.getErrcode match {
      case 0 =>
        res.setSessionKey(jsonObj.get("session_key").getAsString)
        res.setOpenid(jsonObj.get("openid").getAsString)
        val unionid = jsonObj.get("unionid")
        res.setUnionid(if (null == unionid) "" else unionid.getAsString)
      case _ => res.setErrmsg(jsonObj.get("errmsg").getAsString)
    }
    res
  }
}
